package com.yuyou.fn.timer.task;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import com.xxl.job.core.log.XxlJobLogger;
import com.yuyou.fn.common.service.ISiteConfigService;
import com.yuyou.fn.common.util.BigDecimals;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.platform.entity.BusTeam;
import com.yuyou.fn.platform.service.IBusTeamService;
import com.yuyou.fn.settlement.constant.FeeCategoryEnum;
import com.yuyou.fn.settlement.constant.Subjects;
import com.yuyou.fn.settlement.entity.ChangeRecord;
import com.yuyou.fn.settlement.service.IChangeRecordService;
import com.yuyou.fn.settlement.service.ISettlementService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@JobHander(value="DealSpecialCostTask")
@Component
public class DealSpecialCostTask extends IJobHandler {

    @Resource
    private IChangeRecordService changeRecordService;

    @Resource
    private IBusTeamService busTeamService ;

    @Resource
    private ISiteConfigService siteConfigService ;

    @Resource
    private ISettlementService settlementService;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public ReturnT<String> execute(String... params) throws Exception {



        double taxRate = Double.parseDouble(siteConfigService.getConfigValueFromCache("tax_of_campus_cost_rate")) ;
        double manageRate = Double.parseDouble(siteConfigService.getConfigValueFromCache("manage_of_campus_cost_rate")) ;
        double otherRate = Double.parseDouble(siteConfigService.getConfigValueFromCache("other_of_campus_cost")) ;


        Map<String, String> map = redisTemplate.opsForHash().entries("oneDayIncomeChange");
        boolean hasFail = false ;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            Long changeRecordId = Long.parseLong(entry.getValue());
            String key = entry.getKey();
            ChangeRecord changeRecord = changeRecordService.findById(changeRecordId);
            if (changeRecord==null){
                redisTemplate.opsForHash().delete("oneDayIncomeChange", key);
                continue;
            }
            BusTeam busTeam=busTeamService.findById(changeRecord.getMainAccountId());
            if (busTeam==null){
                redisTemplate.opsForHash().delete("oneDayIncomeChange", key);
                continue;
            }
            Date date  = changeRecord.getEffectTime();
            String dateStr = Utils.formatDate(date,"yyyy-MM-dd");
            Date start  = TimeUtils.startOfDate(date);
            Date end  = TimeUtils.endOfDate(date);

            try{
                handle(dateStr, start, end, taxRate, manageRate, otherRate, busTeam);
                redisTemplate.opsForHash().delete("oneDayIncomeChange", key);
            }catch (Exception e){
                hasFail = true;
                XxlJobLogger.log("处理失败:busTeamId={0},date={1},error={2}" , busTeam.getBusTeamId(),dateStr,e.getMessage());
            }

        }

        return hasFail ?  ReturnT.FAIL : ReturnT.SUCCESS;
    }

    private void handle(String dateStr, Date start, Date end, double taxRate, double manageRate, double otherRate, BusTeam busTeam) {
        //统计一天的营收
        BigDecimal amount = changeRecordService.sumBySubjectDirection(busTeam.getBusTeamId(), 0, Subjects.REAL_INCOME, start, end);

        BigDecimal taxAmount=changeRecordService.sumBySubjectCategoryDirection(busTeam.getBusTeamId(), 0, Subjects.COST,FeeCategoryEnum.TAX_OF_CAMPUS_COST.id, start, end);

        /*红冲这些数据*/
        if (taxAmount.doubleValue()>0d){
            settlementService.bookCost( busTeam.getBusTeamId() , FeeCategoryEnum.TAX_OF_CAMPUS_COST.id ,0L ,taxAmount.multiply(new BigDecimal(-1)),busTeam.getName() + "【营业税/刷卡/折旧】红冲-" + dateStr,start );
        }
        BigDecimal manageAmount=changeRecordService.sumBySubjectCategoryDirection(busTeam.getBusTeamId(), 0, Subjects.COST,FeeCategoryEnum.MANAGE_OF_CAMPUS_COST.id, start, end);
        if (manageAmount.doubleValue()>0d){
            settlementService.bookCost( busTeam.getBusTeamId() , FeeCategoryEnum.MANAGE_OF_CAMPUS_COST.id ,0L ,manageAmount.multiply(new BigDecimal(-1)),busTeam.getName() + "【管理费】红冲-" + dateStr,start );
        }
        BigDecimal otherAmount=changeRecordService.sumBySubjectCategoryDirection(busTeam.getBusTeamId(), 0, Subjects.COST,FeeCategoryEnum.OTHER_OF_CMAPUS_COST.id, start, end);
        if (otherAmount.doubleValue()>0d){
            settlementService.bookCost( busTeam.getBusTeamId() , FeeCategoryEnum.OTHER_OF_CMAPUS_COST.id ,0L ,otherAmount.multiply(new BigDecimal(-1)),busTeam.getName() + "【其他成本】红冲-" + dateStr,start );
        }

        if(BigDecimals.compare(amount,BigDecimal.ZERO) == 0 ){
            return;
        }
        //营业税/刷卡/折旧
        settlementService.bookCost( busTeam.getBusTeamId() , FeeCategoryEnum.TAX_OF_CAMPUS_COST.id ,0L ,amount.multiply(BigDecimal.valueOf(taxRate)),busTeam.getName() + "【营业税/刷卡/折旧】-" + dateStr,start );

        //管理费
        settlementService.bookCost( busTeam.getBusTeamId() ,FeeCategoryEnum.MANAGE_OF_CAMPUS_COST.id ,busTeam.getAreaTeamId() ,amount.multiply(BigDecimal.valueOf(manageRate)),busTeam.getName() + "【管理费】-" + dateStr ,start);

        //其他成本
        settlementService.bookCost( busTeam.getBusTeamId() ,FeeCategoryEnum.OTHER_OF_CMAPUS_COST.id ,0L ,amount.multiply(BigDecimal.valueOf(otherRate)),busTeam.getName() + "【其他成本】-" + dateStr ,start);
    }

}
